from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from models.main import *
from models.schema import *

import os
import urllib2
from google.appengine.ext.webapp import template
from google.appengine.ext import db

M.pathes['templates'] = os.path.join(os.path.dirname(__file__), 'templates')

class MainHandler(webapp.RequestHandler):
    def get(self):
		values = {
			'message': 'hi',
			'short_url': 'Short URl'
		}
		self.response.out.write(M.theme('index', values))

class UrlHandler(webapp.RequestHandler):
    def post(self):
		messages = []
		url = self.request.get('url')
		values = {
			'messages': "",
			'url': url,
			'short_url': ''
		}
		if not M.check_url(values['url']):
			messages.append('Invalid URL')
			values['messages'] = M.theme('messages', {'messages': messages})
			self.response.out.write(M.theme('index', values))
			return
		query = db.Query(ShortenUrl)
		query.filter('long_url = ', url)
		results = query.fetch(1);
		if len(results) > 0:
			db_url = results[0]
			db_url.refferals += 1
			messages.append('Your URL has been already added before. Follow this link.')
		else:
			db_url = ShortenUrl(long_url = url, refferals = 1)
			messages.append('Your URL was added.')
		db_url.put()
		if len(messages) > 0:
			values['messages'] = M.theme('messages', {'messages': messages})
		self.response.out.write(M.theme('index', values))
		return
		
def main():
    application = webapp.WSGIApplication(
		[
			('/', MainHandler),
			('/url', UrlHandler)
		],
        debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
